package com.songhq.netty.two;

import java.net.InetSocketAddress;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * 
 * 引导服务器
 * 
 * @author Administrator
 *
 */
public class EchoServer {

	

	static private final int port = 8080;
	
	
	public static void main(String[] args) throws InterruptedException {
		new EchoServer().start();
	}

	public void start() throws InterruptedException {

		final EchoServerHandler serverHandler = new EchoServerHandler();
		// 创建EventLoopGroup
		NioEventLoopGroup group = new NioEventLoopGroup();

		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(group)
					// 指定使用NIO传输通道
					.channel(NioServerSocketChannel.class)
					// 使用指定的端口地址
					.localAddress(new InetSocketAddress(port))
					// 添加一个EchoServerHandler到channel的ChannelPipeline
					.childHandler(new ChannelInitializer<SocketChannel>() {

						@Override
						protected void initChannel(SocketChannel ch) throws Exception {
							ch.pipeline().addLast(serverHandler);
						}
					});
			// 异步的绑定服务器，调用sync()方法阻塞，直到绑定完成
			ChannelFuture f = b.bind().sync();
			// 获取channel的CloseFuture，阻塞直到完成
			f.channel().closeFuture().sync();
		} finally {
			// 关闭NioEventLoopGroup，释放所有的资源
			group.shutdownGracefully().sync();
		}

	}

}
